package main

import (
	"fmt"

	"github.com/hashicorp/consul/api"
)

func Register(address string, port int, name string, tags []string, id string) {
	cfg := api.DefaultConfig()
	cfg.Address = "47.113.109.37:8500"

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	//生成对应的检查对象
	check := &api.AgentServiceCheck{
		HTTP: "http://221.5.88.88:8021/health",
		Timeout: "5s",
		Interval: "5s",
		DeregisterCriticalServiceAfter: "10s",
	}

	// 生成注册对象
	registration := new(api.AgentServiceRegistration)
	registration.Name = name
	registration.ID = id
	registration.Port = port
	registration.Tags = tags
	registration.Address = address
	registration.Check = check

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}
}

func AllService(){
	cfg := api.DefaultConfig()
	cfg.Address = "47.113.109.37:8500"

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	data, err := client.Agent().Services()
	if err != nil {
		panic(err)
	}

	for key, _ := range data {
		fmt.Println(key)
	}
}

func FilterService () {
	cfg := api.DefaultConfig()
	cfg.Address = "47.113.109.37:8500"

	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	//data, err := client.Agent().ServicesWithFilter(`Service == "shop-web"`)
	data, err := client.Agent().ServicesWithFilter(`Service == "user-srv"`)
	if err != nil {
		panic(err)
	}

	for key, d := range data {
		fmt.Println(key, d)
	}
}

func main() {
	//Register("221.5.88.88", 8021, "user-web", []string{"ice", "shop"}, "shop-web")
	//AllService()
	FilterService()
}